package main

import (
	"fmt"
	"os"
	"os/exec"
	"sync"
	"time"
)

func startServer(port string, apiFlag string, wg *sync.WaitGroup) {
	defer wg.Done()

	// 启动服务器
	cmd := exec.Command("./server.exe", "-port="+port, apiFlag)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Start()
	if err != nil {
		fmt.Println("Error starting server on port", port, ":", err)
	}
	// fmt.Printf("Server started on port %s\n", port)
}

func startCurlRequest(wg *sync.WaitGroup, url string) {
	defer wg.Done()

	// 使用 curl.exe 执行请求
	cmd := exec.Command("curl.exe", "-s", url)
	output, err := cmd.CombinedOutput()
	if err != nil {
		fmt.Println("Error executing curl request:", err)
	} else {
		fmt.Println(string(output))
	}
}

func main() {
	// 启动 3 个服务并显示日志
	var wg sync.WaitGroup
	fmt.Println(">>> starting servers...")

	wg.Add(3)
	go startServer("8001", "", &wg)       // 8001 不带 api
	go startServer("8002", "", &wg)       // 8002 不带 api
	go startServer("8003", "-api=1", &wg) // 8003 带 api

	// 等待 2 秒确保服务启动
	time.Sleep(2 * time.Second)

	// 执行 curl 请求
	fmt.Println(">>> start test")

	wg.Add(3)
	url := "http://localhost:9999/api?key=Tom"
	for i := 0; i < 3; i++ {
		go startCurlRequest(&wg, url)
	}

	// 等待所有请求完成
	wg.Wait()

	// 输出结果
	fmt.Println("\n>>> all tests finished")

	// 停止服务器
	fmt.Println(">>> stopping servers...")
	cmd := exec.Command("taskkill", "/F", "/IM", "server.exe")
	err := cmd.Run()
	if err != nil {
		fmt.Println("Error stopping servers:", err)
	}
}

// go build  -o run.exe .\run\run.go
